<?php

namespace app\home\controller;

use app\common\UserModel;
use dingtalk\Auth;
use think\Controller;
use think\Cookie;
use think\Request;

class PublicController extends Controller
{
    private $accessToken;
    private $jsTicket;
    private $userModel;

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->accessToken = Auth::getAccessToken();
        $this->jsTicket = Auth::getTicket($this->accessToken);
        $this->userModel = new UserModel();
    }

    /**
     * 获取授权用户
     * @return mixed
     */
    public function auth()
    {
        if ($this->request->isAjax()) {
            $code = $this->request->param('code');
            $response = Auth::getUserId($this->accessToken, $code);
            if ($response['errcode'] != 0) {
                $this->error('errmsg');
            }
            $userinfo = $this->userModel->where('userid', $response['userid'])->find();
            if ($userinfo) {
                Cookie::set('user', $userinfo->toArray(), 3600 * 24);
                $this->success('操作成功！');
            } else {
                $this->error('[' . $userinfo['name'] . ']还未同步！');
            }
        }
        if (Cookie::has('user')) {
            $this->redirect('Index/index');
        } else {
            return $this->fetch();
        }
    }

    /**
     * 清除登录信息
     */
    public function clearCookie()
    {
        Cookie::delete('user');
        $this->success('清除登录信息！');
    }
    /***************************远程调用相关************************************/
    public function getToken(){
        return $this->accessToken;
    }
    public function getJsTicket(){
        return $this->jsTicket;
    }

}
